import axios from "axios";

/**
 * 获取github热门项目列表
 * @param q 查询条件,格式如:"stars:>1 language:javascript"
 * @param pageNum 页码,从1开始
 * @returns {Promise<{code:200|500|number,desc:string,data:any}>}
 */
export async function githubRepositories(q, pageSize = 32, pageNum = 1) {
  try {
    const res = await axios.get(
      `https://api.github.com/search/repositories?q=${encodeURIComponent(
        q
      )}&sort=stars&order=desc&type=Repositories&page=${pageNum}&per_page=${pageSize}`
    );
    if (res.status !== 200) {
      return { code: res.status, desc: res.statusText };
    }
    return { code: 200, data: res.data };
  } catch (err) {
    return { code: 500, desc: err?.message ?? err };
  }
}
/**
 * 查询单个用户, 结果的data直接为用户的json
 * 格式参考: https://api.github.com/users/用户名
 */
export async function githubUser(username) {
  try {
    const res = await axios.get(
      `https://api.github.com/users/${encodeURIComponent(username)}`
    );
    if (res.status === 404) {
      return { code: res.status, desc: "不存在的用户名!" };
    }
    if (res.status !== 200) {
      return { code: res.status, desc: res.statusText };
    }
    return { code: 200, data: res.data };
  } catch (err) {
    if (err.response) {
      if (err.response.status === 404) {
        return { code: err.response.status, desc: "不存在的用户名!" };
      }
    }
    return { code: 500, desc: err?.message ?? err };
  }
}

export default {};
